#pragma once

#include <windows.h>
#include <string>

/*
Class: NamedPipeClient
	A sample implementation of a client pipe that communicates with the hook server.
*/
typedef struct
{
	DWORD       dwOfs;
    DWORD       dwData;
}KeyInfo,*PKeyInfo;

class NamedPipeClient
{
public:
	NamedPipeClient(const TCHAR* pipeName) : m_pipeName(pipeName), m_pipe(INVALID_HANDLE_VALUE)
	{
	}

	~NamedPipeClient()
	{
		Disconnect();
	}

	bool IsServerAvailable()
	{
		return WaitNamedPipe(m_pipeName.c_str(), NMPWAIT_USE_DEFAULT_WAIT);
	}

	bool Connect()
	{
		m_pipe = CreateFile(m_pipeName.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL, 0);

		return m_pipe != INVALID_HANDLE_VALUE;
	}

	bool Write(PKeyInfo keys,int count)
	{
		DWORD numBytesWritten;
		return WriteFile(m_pipe, keys, sizeof(KeyInfo)*count, &numBytesWritten, 0) && numBytesWritten == sizeof(KeyInfo)*count;
	}

	void Disconnect()
	{
		if(m_pipe != INVALID_HANDLE_VALUE)
		{
			CloseHandle(m_pipe);
			m_pipe = INVALID_HANDLE_VALUE;
		}
	}

private:
	std::basic_string<TCHAR> m_pipeName;
	HANDLE m_pipe;
};
